﻿using System;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;

namespace OpenXmlEasy.Common
{
    public class HtmlHelper
    {
        public Image GetImageFromBase64String(string imageText)
        {
            if (string.IsNullOrEmpty(imageText))
            {
                return null;
            }
            //bitmapData = Convert.FromBase64String(FixBase64ForImage(ImageText));
            byte[] bitmapData = Convert.FromBase64String(imageText);
            var streamBitmap = new MemoryStream(bitmapData);
            //    Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(streamBitmap));
            return Image.FromStream(streamBitmap);
        }

        public string RemoveHtml(string htmlstring)
        {
            //删除脚本
            htmlstring = Regex.Replace(htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML            
            htmlstring = Regex.Replace(htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

            htmlstring = Regex.Replace(htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            //Htmlstring.Replace("<", "");
            //Htmlstring.Replace(">", "");
            //Htmlstring.Replace("\r\n", "");

            //var htmlEncode = HttpContext.Current.Server.HtmlEncode(htmlstring);
            //if (htmlEncode != null)
            //    htmlstring = htmlEncode.Trim();

            return htmlstring;
        }
    }
}
